import { type PlasmoMessaging } from "@plasmohq/messaging"

let response: PlasmoMessaging.Response<any> | null = null
let targetTab: chrome.tabs.Tab | null = null

/**
 * 获取天眼查的企业联系方式
 */
const handler: PlasmoMessaging.MessageHandler = async (req, res) => {
  const { company_name, isTYC, data } = req.body
  if (isTYC && response) {
    chrome.tabs.remove(targetTab?.id)
    response?.send(data)
  } else {
    response = res
    const { value: authToken } = await chrome.cookies.get({ url: "https://www.tianyancha.com", name: "auth_token" })
    const listUrl = `https://www.tianyancha.com/nsearch?key=${company_name}&auth_token=${authToken}`
    const url = authToken ? listUrl : "https://www.tianyancha.com/login"
    targetTab = await chrome.tabs.create({ url, active: !authToken })
  }
}

export default handler
